//
//  JCContentlistViewController.swift
//  JCNewsForMac
//
//  Created by ifly on 16/8/18.
//  Copyright © 2018年 Ismail. All rights reserved.
//

import Cocoa


class JCContentlistViewController: NSViewController {
    
    private var jcContentListArray = Array<JCContentModel>()
    
    private var jcSelertModel:JCContentModel?
    
    private var jcItemTitleArray = ["设置默认","添加到爆款热卖","添加到精品推荐","添加到限时特惠"]
    
    private var jcType = 0
    
    //MARK:最根部的NSSplitView
    private lazy var jcSplitView:NSSplitView = {
        
        var jcSplitView = NSSplitView.init(frame: self.view.frame)
        jcSplitView.isVertical = true
        jcSplitView.dividerStyle = .thick
        jcSplitView.delegate = self
        
        return jcSplitView
    }()
    
    //    MARK:左边的背景view
    private lazy var jcLeftView:NSView = {
        var leftView = NSView.init(frame: CGRect.init(x: 0, y: 0, width: 600, height: self.view.frame.size.height))
        leftView.wantsLayer = true
        leftView.layer?.backgroundColor = NSColor.white.cgColor
        return leftView
    }()
    
    //    MARK: 类型选择框
    private lazy var jcTypeComboBox:NSComboBox = {
        
        var jcTypeComboBox = NSComboBox.init(frame: CGRect.init(x: 200, y: self.view.frame.size.height - 45, width: 130, height: 35))
        jcTypeComboBox.isEditable = false
//        jcTypeComboBox.isBordered = false
        jcTypeComboBox.numberOfVisibleItems = 5
        jcTypeComboBox.addItems(withObjectValues: ["全部","爆款热卖","精品推荐","限时特惠"])
        jcTypeComboBox.selectItem(withObjectValue: "全部")
        jcTypeComboBox.font = NSFont.systemFont(ofSize: 16)
        jcTypeComboBox.tag = 100
        jcTypeComboBox.delegate = self
        
        return jcTypeComboBox;
    }()
    
    
    //   MARK:NSSplitView 左边部分NSScrollView
    private lazy var jcLeftScrView:NSScrollView = {
        //        定义ScrollView，NSTableView的滑动必须依附在ScrollView上
        var jcLeftScrView = NSScrollView.init(frame: CGRect.init(x: 0, y: 0, width: 600, height: self.view.frame.size.height - 40))
        jcLeftScrView.drawsBackground = true
        jcLeftScrView.hasVerticalScroller = true
        jcLeftScrView.autohidesScrollers = true
        return jcLeftScrView
    }()
    
    //    MARK:定义 NSTableView
    private lazy var jcLeftTabelview:NSTableView = {
        
        var rootabelview = NSTableView.init(frame: CGRect.init(x: 0, y: 0, width: 600, height: self.view.frame.size.height - 40))
        rootabelview.focusRingType = NSFocusRingType.default//tableview获得焦点时的风格
        rootabelview.selectionHighlightStyle = .regular //行高亮的风格
        rootabelview.backgroundColor  = NSColor.orange
        rootabelview.usesAlternatingRowBackgroundColors = true //背景颜色的交替，一行白色，一行灰色。设置后，原来设置的 backgroundColor 就无效了。
        rootabelview.delegate = self
        rootabelview.dataSource = self
        rootabelview.gridColor = NSColor.magenta
        rootabelview.rowHeight = 125
       
        
        return rootabelview
    }()
    
    
    //   MARK:NSSplitView的右边部分 NSView
    private lazy var jcRightView:NSView = {
        var rigtView = NSView.init(frame: CGRect.init(x: 0, y: 0, width: 400, height: self.view.frame.size.height))
        return rigtView
    }()
    
    
    private lazy var jcRightScrView:NSScrollView = {
        
        var jcRightScrView = NSScrollView.init(frame: CGRect.init(x: 0, y: 100, width: 400, height: self.view.frame.size.height - 100))
        return jcRightScrView
    }()
    
    private lazy var jcCollectionView: NSCollectionView = {
        
        let flowLayout = NSCollectionViewFlowLayout.init()
        flowLayout.scrollDirection = .vertical  // 设置排列方式
        flowLayout.sectionInset = NSEdgeInsets.init(top: 16, left: 16, bottom: 16, right: 18)
        flowLayout.minimumLineSpacing = 10
        flowLayout.minimumInteritemSpacing = 10
        
        var collection = NSCollectionView.init()
        collection.collectionViewLayout = flowLayout    // 指定布局
        collection.isSelectable = true                  // item是否可以点击
        
        return collection
    }()

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do view setup here.
        
        view.addSubview(jcSplitView)
                
        title = "宣传单管理"
        
        jcSplitView.addSubview(jcLeftView)
        jcSplitView.addSubview(jcRightView)
        
        jcLeftView.addSubview(jcLeftScrView)
        jcLeftView.addSubview(jcTypeComboBox)
        
        jcRightView.addSubview(jcRightScrView)
        
        jcLeftScrView.documentView = jcLeftTabelview
        jcRightScrView.documentView = jcCollectionView
        
        let colum1 = NSTableColumn.init(identifier: NSUserInterfaceItemIdentifier(rawValue: "columnFrist"))
        colum1.title = "\t宣传单筛选结果"
        colum1.width = 600
        jcLeftTabelview.addTableColumn(colum1)
        
        jcCollectionView.delegate = self
        jcCollectionView.dataSource = self
        jcCollectionView.register(JCCollectionViewItem.self, forItemWithIdentifier: NSUserInterfaceItemIdentifier(rawValue: "JCCollectionViewItem"))  // 注册Item 和NSCollectionView类似
        
        jcGetContentList()
    }
    
    private func jcGetContentList(){
        
        jcContentListArray.removeAll()
        
        JCAPI.jcGetContentList(1, pageSize: 0, Contentlabel: "", HotType: jcType, success: { (jsonDate) in
            
            for itme in jsonDate{
                let model:JCContentModel = JCContentModel.deserialize(from: itme as? NSDictionary)!
                self.jcContentListArray.append(model)
            }
            self.jcLeftTabelview.reloadData()
            
        }) { (errString, errCode) in
            
        }
    }
    
    func jcSetContentState(_ jcState:Int) -> Void {
    
        let jcAlert = NSAlert.init()
        jcAlert.addButton(withTitle: "确定")
        jcAlert.messageText = "系统提示"
        jcAlert.alertStyle = NSAlert.Style.informational
        
        JCAPI.jcSetContentState(jcSelertModel!.ContentId, contentState: jcState, success: { (jsonData) in
            jcAlert.informativeText = "宣传单设置成功！"
            jcAlert.beginSheetModal(for: self.view.window!, completionHandler: {_ in
            })
            
        }) { (errString, errCode) in
            
            jcAlert.informativeText = "宣传单设置失败！\(errCode)"
            jcAlert.beginSheetModal(for: self.view.window!, completionHandler: {_ in
            })
        }
    }
    
}
//MARK:NSSplitView 代理
extension JCContentlistViewController:NSSplitViewDelegate{
//
    func splitView(_ splitView: NSSplitView, constrainMaxCoordinate proposedMaximumPosition: CGFloat, ofSubviewAt dividerIndex: Int) -> CGFloat {
        if dividerIndex == 0 {
            return 600
        }else{
            return CGFloat(MAXFLOAT)
        }
    }

    func splitView(_ splitView: NSSplitView, constrainMinCoordinate proposedMinimumPosition: CGFloat, ofSubviewAt dividerIndex: Int) -> CGFloat{

        if dividerIndex == 0 {
            return 600
        }else{
            return 200
        }
    }
    
}
//MARK:NSComboBox 代理
extension JCContentlistViewController:NSComboBoxDelegate{
    
    func comboBoxSelectionDidChange(_ notification: Notification) {
        
        let jcView:NSComboBox = notification.object as! NSComboBox
        jcType = jcView.indexOfSelectedItem
        
        jcGetContentList()
    }
    
    func comboBoxSelectionIsChanging(_ notification: Notification) {
        //        let jcView:NSComboBox = notification.object as! NSComboBox
        //        print("===2222222222222222==========",jcView.indexOfSelectedItem)
    }
    
    
}

//MARK:NSTableView 代理方法
extension JCContentlistViewController:NSTableViewDelegate,NSTableViewDataSource{
    
    func numberOfRows(in tableView: NSTableView) -> Int {
        return jcContentListArray.count
    }
    
    func tableView(_ tableView: NSTableView, shouldSelectRow row: Int) -> Bool {
        return true
    }

    //MARK:自定义cell
    func tableView(_ tableView: NSTableView, viewFor tableColumn: NSTableColumn?, row: Int) -> NSView? {
        
        var cell:JCContentCellView? = tableView.makeView(withIdentifier: NSUserInterfaceItemIdentifier.init("columnFrist"), owner: self) as? JCContentCellView
        if cell == nil {
            cell = JCContentCellView.init(frame: CGRect.init(x: 0, y: 0, width: 300, height: 140))
            cell?.identifier = NSUserInterfaceItemIdentifier(rawValue: "columnFrist")
        }
        cell?.setData(jcContentListArray[row])
        return cell!
    }
    //
    func tableView(_ tableView: NSTableView, rowViewForRow row: Int) -> NSTableRowView? {
        var rowView:NSTableRowView? = tableView.makeView(withIdentifier: NSUserInterfaceItemIdentifier.init("RowView"), owner: self) as? NSTableRowView
        if rowView == nil {
            rowView = NSTableRowView.init()
            rowView?.identifier = NSUserInterfaceItemIdentifier(rawValue: "RowView")
        }
        rowView?.backgroundColor = NSColor.red
        
        return rowView
    }
    
    func tableViewSelectionDidChange(_ notification: Notification) {
        
        let tableview:NSTableView = notification.object as! NSTableView
//        tableview.deselectRow(tableview.selectedRow)
        print("======",tableview.selectedRow)
        jcSelertModel = jcContentListArray[tableview.selectedRow]
    }
    
}


extension JCContentlistViewController: NSCollectionViewDataSource, NSCollectionViewDelegate {
    // 返回Item个数
    func collectionView(_ collectionView: NSCollectionView, numberOfItemsInSection section: Int) -> Int {
        return jcItemTitleArray.count
    }

    func collectionView(_ collectionView: NSCollectionView, itemForRepresentedObjectAt indexPath: IndexPath) -> NSCollectionViewItem {
        let item:JCCollectionViewItem = collectionView.makeItem(withIdentifier: NSUserInterfaceItemIdentifier(rawValue: "JCCollectionViewItem"), for: indexPath) as! JCCollectionViewItem
        
        item.view.wantsLayer = true
        item.view.layer?.backgroundColor = NSColor.orange.cgColor
        item.jcTitle.stringValue = jcItemTitleArray[indexPath.item]
        return item
    }
    // 点击方法
    func collectionView(_ collectionView: NSCollectionView, didSelectItemsAt indexPaths: Set<IndexPath>) {
        print("items select",indexPaths)
        
        collectionView.deselectItems(at: indexPaths)
        
        let indexPath = indexPaths.first
        
        if self.jcSelertModel != nil {
            jcSetContentState(indexPath!.item)
        }else{
            let jcAlert = NSAlert.init()
            jcAlert.addButton(withTitle: "确定")
            jcAlert.messageText = "系统提示"
            jcAlert.alertStyle = NSAlert.Style.informational
            jcAlert.informativeText = "请选择宣传单在进行操作！"
            jcAlert.beginSheetModal(for: self.view.window!, completionHandler: {_ in
            })
        }
        
    }
    
}
// NSCollectionView的布局方法
extension JCContentlistViewController: NSCollectionViewDelegateFlowLayout {
    // 返回Item的size
    func collectionView(_ collectionView: NSCollectionView, layout collectionViewLayout: NSCollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> NSSize {
        return NSSize.init(width: 160, height: 60)
    }
}


